package com.luo;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
 * @Author: luosiyu
 * @Description: Math计算器
 * @Version: 1.0
 */
public class DemoMath {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
        Scanner scanner = new Scanner(System.in);
        while (true){
            System.out.println("请输入计算方法：");
            String str = scanner.nextLine();
            if (str == "1") {
                break;
            }
            System.out.println(myMath(str));
        }
    }

    public static Object myMath(String s) throws ClassNotFoundException, InvocationTargetException, IllegalAccessException {
        /**
        * @Description: 根据输入的值调用相应的math方法，查找出math的所有方法，循环遍历，选择输入的对应方法
        * @param s :调用的方法
        * @return: [java.lang.String]
        */
        Scanner scanner = new Scanner(System.in);
        Class<Math> mathClass = Math.class;
        Method[] methods = mathClass.getDeclaredMethods();
        if (methods != null) {
            for (Method met : methods) {
                Method method = met;
                if (s.equals(method.getName())) {
                    Class<?>[] params = method.getParameterTypes();//获取形参类型
                    for (Class<?> aClass : params) {
                        if(aClass.getName().equals("double")) {
                            if (params.length == 1) {
                                System.out.println("请输入计算的数字：");
                                double dob = scanner.nextDouble();
                                return method.invoke(mathClass,dob);
                            }
                            if(params.length == 2) {
                                System.out.println("请输入计算的数字1：");
                                double dob1 = scanner.nextDouble();
                                System.out.println("请输入计算的数字2：");
                                double dob2 = scanner.nextDouble();
                                return method.invoke(mathClass,dob1,dob2);
                            }
                        }
                    }
                }
            }
        }
        return "没有调用该类型方法";
    }

}
